package com.ylbh.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description:
 * @Date: Created in 2018/7/31 17:36
 * @Author: Wangll
 */
public class SmsUtils {
    //产品名称:云通信短信API产品
    static final String product = "Dysmsapi";

    //产品域名,
    static final String domain = "dysmsapi.aliyuncs.com";

    // accessKeyId
//    static final String accessKeyId = "LTAI4hzAnmK0zVdt";
    static final String accessKeyId = "LTAIwSynClEKZSWc";

    // accessKeySecret
//    static final String accessKeySecret = "BZHoFPAXee4YiJ0960E5JtNetxX50n";
    static final String accessKeySecret = "k9JCzDEVi39tMFO6MIq88XujeWtTKw";

    //短信验证码登录 SMS_137668083
    public static final String SMS_LOGIN = "SMS_158945248";

    //注册验证码 SMS_80015007
    public static final String SMS_REGISTER = "SMS_158940272";

    //重置密码 SMS_83040004
    public static final String SMS_RESET = "SMS_158940271";

    //新用户注册后发送密码
    public static final String SMS_NEW_USER_PASSWORD = "SMS_152851834";

    // 换绑手机号
    public static final String SMS_RESET_IPHONE = "SMS_152825005";

    //短信签名
    public static final String signName = "送贝";

    //商家提现提醒
    public static final String SMS_WITH_NOTICE = "SMS_152211123";

    //商家提现拒绝后提醒
    public static final String SMS_NOT_WITH_NOTICE = "SMS_152286839";

    //通知跑腿员店家的跑腿订单应急
    public static final String SMS_BUSINESS_RUNNING_NOTICE = "SMS_162547290";

    //发送短信
    public static CommonResult<Object> sendSms(String iphone, String signName, String templateCode, String code) {

        //可自助调整超时时间

        //System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        //System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            return Ref.error("发送短信失败");
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(iphone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            return Ref.error("发送短信失败");
        }
        return Ref.ok(sendSmsResponse);
    }


    public static String batchSendSms(String iphone, String contents){
        //请求第三方平台连接
        String url = "http://www.mxtong.net.cn/GateWay/Services.asmx/DirectSend?";
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
        PostMethod getMethod = new PostMethod(url);
        try {//设置短信内容，短信内容格式 签名+内容+提示退订
            String content= java.net.URLEncoder.encode("【亿联百汇】"+contents+"回T退订", "UTF-8");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            NameValuePair[] data = {
                    new NameValuePair("UserID", "911095"),//用户ID
                    new NameValuePair("Account", "admin"),//字用户名
                    new NameValuePair("Password", "2JLANL"),//密码
                    new NameValuePair("Phones", iphone),//要发送的电话号码 "18665962906;13560452807;18123313611;"
                    new NameValuePair("SendType", "1"),//发送类型默认为1
                    new NameValuePair("SendTime", ""),//设置定时发送  ""为立即发送
                    new NameValuePair("PostFixNumber", ""),//任务扩展号(1到9,或者为空)
                    new NameValuePair("Content", content) };//短信内容
            getMethod.setRequestBody(data);
            getMethod.addRequestHeader("Connection", "close");
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "+ getMethod.getStatusLine());
            }
            byte[] responseBody = getMethod.getResponseBody();
            String str = new String(responseBody, "utf-8");
            if (str.contains("GBK")) {
                str = str.replaceAll("GBK", "utf-8");
            }
            int beginPoint = str.indexOf("<RetCode>");
            int endPoint = str.indexOf("</RetCode>");
            return str.substring(beginPoint + 9, endPoint);//返回Sucess  Faild
        } catch (Exception e) {
            return "Faild";
        } finally {
            getMethod.releaseConnection();
        }
    }

    //发送指定模板格式短信
    public static CommonResult<Object> sendTemplateSms(String iphone,String signName,String templateCode,String jsonTemplate){

        //可自助调整超时时间
        //System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        //System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            return Ref.error("发送短信失败");
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(iphone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(jsonTemplate);
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            return  Ref.error("发送短信失败");
        }
        return Ref.ok(sendSmsResponse);
    }


    //发送短信
    public static CommonResult<Object> sendStore(String iphone,String signName,String templateCode,String name,String code){

        //可自助调整超时时间
        //System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        //System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            return Ref.error("发送短信失败");
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(iphone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"name\":\"" + name + "\",\"code\":\""+code+"\"}");
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            return Ref.error("发送短信失败");
        }
        return Ref.ok(sendSmsResponse);
    }



}
